// 保存当前倍率到存储
function saveCurrentSpeedRate(speedRate) {
  localStorage.setItem("bilibiliVideoSpeedRateCurrent", speedRate.toString());
}

// 从存储中获取上次的倍率
function getLastSpeedRate() {
  const savedRate = localStorage.getItem("bilibiliVideoSpeedRateCurrent");
  return savedRate ? parseFloat(savedRate) : 1; // 默认1倍速
}

// 恢复上次的倍率设置
function restoreLastSpeedRate() {
  const lastRate = getLastSpeedRate();
  const videoDomSelector =
    "#bilibili-player > div > div > div.bpx-player-primary-area > div.bpx-player-video-area > div.bpx-player-video-perch > div > video";
  const videoDom = document.querySelector(videoDomSelector);

  if (videoDom && lastRate !== 1) {
    videoDom.playbackRate = lastRate;
    console.log(`已恢复倍率: ${lastRate}x`);
  }
}

function changSpeedRateList(mySpeedList = null) {
  if (!mySpeedList) {
    const defaultList = [0.5, 0.75, 1, 1.25, 1.5, 2, 3, 4, 5, 16];
    const storageList = localStorage.getItem("bilibiliVideoSpeedRateList");
    if (storageList) {
      mySpeedList = JSON.parse(storageList);
    } else {
      mySpeedList = defaultList;
    }
  }
  localStorage.setItem(
    "bilibiliVideoSpeedRateList",
    JSON.stringify(mySpeedList)
  );

  const videoDomSelector =
    "#bilibili-player > div > div > div.bpx-player-primary-area > div.bpx-player-video-area > div.bpx-player-video-perch > div > video";
  const speedListSelector =
    "#bilibili-player > div > div > div.bpx-player-primary-area > div.bpx-player-video-area > div.bpx-player-control-wrap > div.bpx-player-control-entity > div.bpx-player-control-bottom > div.bpx-player-control-bottom-right > div.bpx-player-ctrl-btn.bpx-player-ctrl-playbackrate > ul";
  const videoDom = document.querySelector(videoDomSelector);
  const speedListDom = document.querySelector(speedListSelector);
  const speedItemDom = speedListDom.firstElementChild;
  speedListDom.innerHTML = "";

  // 获取上次保存的倍率
  const lastRate = getLastSpeedRate();

  mySpeedList
    .sort((a, b) => b - a)
    .forEach((item) => {
      const node = speedItemDom.cloneNode();
      node.setAttribute("data-value", item);
      node.innerText = `${item}x`;

      // 如果当前项是上次保存的倍率，添加选中样式
      if (item === lastRate) {
        node.style.backgroundColor = "#00a1d6";
        node.style.color = "#fff";
      }

      node.addEventListener("click", () => {
        videoDom.playbackRate = item;
        saveCurrentSpeedRate(item); // 保存当前选择的倍率

        // 更新选中状态
        speedListDom.querySelectorAll("li").forEach((li) => {
          li.style.backgroundColor = "";
          li.style.color = "";
        });
        node.style.backgroundColor = "#00a1d6";
        node.style.color = "#fff";
      });
      speedListDom.appendChild(node);
    });

  // 恢复上次的倍率
  restoreLastSpeedRate();
  console.log("bilibiliVideoSpeedRate已注入");
}

// 监听视频切换事件
function setupVideoChangeListener() {
  const videoDomSelector =
    "#bilibili-player > div > div > div.bpx-player-primary-area > div.bpx-player-video-area > div.bpx-player-video-perch > div > video";

  // 使用MutationObserver监听视频元素的变化
  const observer = new MutationObserver((mutations) => {
    mutations.forEach((mutation) => {
      if (mutation.type === "childList") {
        mutation.addedNodes.forEach((node) => {
          if (node.nodeType === Node.ELEMENT_NODE) {
            const video = node.querySelector
              ? node.querySelector("video")
              : null;
            if (video || node.tagName === "VIDEO") {
              const targetVideo = video || node;
              // 延迟恢复倍率，确保视频已加载
              setTimeout(() => {
                restoreLastSpeedRate();
              }, 500);
            }
          }
        });
      }
    });
  });

  // 监听播放器容器的变化
  const playerContainer = document.querySelector("#bilibili-player");
  if (playerContainer) {
    observer.observe(playerContainer, {
      childList: true,
      subtree: true,
    });
  }

  // 监听视频的loadstart事件
  const videoDom = document.querySelector(videoDomSelector);
  if (videoDom) {
    videoDom.addEventListener("loadstart", () => {
      setTimeout(() => {
        restoreLastSpeedRate();
      }, 300);
    });
  }
}

const repeatImplement = (times = 5) => {
  setTimeout(() => {
    try {
      changSpeedRateList();
      setupVideoChangeListener(); // 设置视频切换监听
    } catch (err) {
      if (times > 0) repeatImplement(times--);
    }
  }, 1000);
};

repeatImplement();

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  const { action, data } = request;
  sendResponse({ state: "视频倍速列表已更新" });
  if (action === "setSpeedList") {
    changSpeedRateList(data.split("、"));
  }
});
